import 'dart:convert';
import 'package:flutter/foundation.dart';

import "./lib_http_httpUtil.dart";

const host = "http://127.0.0.1:8000";
get(url, data, cb, errCallback) {
  HttpUtil.getInstance().get(host + url, data, (responseData) {
    var parsedData = responseData is String ? jsonDecode(responseData) : responseData;
    cb(parsedData);
  }, errCallback);
}

delete1(url, data, cb, errCallback) {
  HttpUtil.getInstance().delete1(host + url, data, (responseData) {
    var parsedData = responseData is String ? jsonDecode(responseData) : responseData;
    cb(parsedData);
  }, errCallback);
}

post(url, data, cb, errCallback) {
  HttpUtil.getInstance().post(host + url, data, (responseData) {
    var parsedData = responseData is String ? jsonDecode(responseData) : responseData;
    cb(parsedData);
  }, errCallback);
}

put(url, data, cb, errCallback) {
  HttpUtil.getInstance().put(host + url, data, (responseData) {
    var parsedData = responseData is String ? jsonDecode(responseData) : responseData;
    cb(parsedData);
  }, errCallback);
}

postOrPut(url, data, cb, errCallback) {
  if (data.id) {
    HttpUtil.getInstance().put(host + url, data, (responseData) {
      var parsedData = responseData is String ? jsonDecode(responseData) : responseData;
      cb(parsedData);
    }, errCallback);
  } else {
    HttpUtil.getInstance().post(host + url, data, (responseData) {
      var parsedData = responseData is String ? jsonDecode(responseData) : responseData;
      cb(parsedData);
    }, errCallback);
  }
}

void postForm(url, data, cb, errCallback) {
  HttpUtil.getInstance().postForm(host + url, data, (responseData) {
    var parsedData = responseData is String ? jsonDecode(responseData) : responseData;
    cb(parsedData);
  }, errCallback);
}

contacts(data, cb, errCallback) {
  return get('/rest/Contact/', data, cb, errCallback);
}

usePacks(query, cb, errCallback) {
  var data = {"contact": query};
  return get('/rest/UsePack/', data, cb, errCallback);
}

packItems(data, cb,errCallback) {
  return get('/rest/PackItem/', data, cb, errCallback);
}

items(data, cb,errCallback) {
  return get('/rest/Item/', data, cb, errCallback);
}

packs(data, cb, errCallback) {
  return get('/rest/Pack/', data, cb, errCallback);
}

packDelete(data, cb, errCallback) {
  return delete1('/rest/Pack/', data, cb, errCallback);
}

packUpdate(data, cb, errCallback) {
  return put('/rest/Pack/', data, cb, errCallback);
}

packCreate(data, cb, errCallback) {
  return post('/rest/Pack/', data, cb, errCallback);
}

loginIndex(username, password, cb, errcallback) {
  //var uri = Uri.http(host, '/rest/login_index');
  HttpUtil.getInstance().get(host + '/rest/login_index/', null, (r) {
    // 从响应中解析CSRF token
    Map<String, dynamic> responseData;
    try {
      if (r is String) {
        responseData = jsonDecode(r) as Map<String, dynamic>;
      } else if (r is Map<String, dynamic>) {
        responseData = r;
      } else {
        throw FormatException('Unexpected response type: ${r.runtimeType}');
      }
      
      String csrfToken = responseData['csrf_token'];
      if (csrfToken == null || csrfToken.isEmpty) {
        throw FormatException('CSRF token not found in response');
      }
      
      login_true(username, password, csrfToken, cb, errcallback);
    } catch (e) {
      print('解析登录响应失败: $e');
      if (errcallback != null) {
        errcallback(e);
      }
    }
  }, errcallback);
}

login(username, password, cb, errcallback) {
  loginIndex(username, password, cb, errcallback);
}

logout(cb) {
  return get('/rest/logout/', null, cb, null);
}

login_true(username, password, csrfToken, cb, errCallback) {
  //post form，包含CSRF token
  var data = {
    "username": username,
    "password": password,
    "csrfmiddlewaretoken": csrfToken, // 添加CSRF token字段
  };
  
  // 获取HttpUtil的dio实例
  var dio = HttpUtil.getInstance().dio;
  
  // 为所有平台设置CSRF Token头
  // 在Web平台上，Dio会自动处理Cookie，我们只需要确保设置了正确的头
  dio.options.headers["X-CSRFToken"] = csrfToken;
  
  // 对于Web平台，我们可以添加额外的安全头
  if (kIsWeb) {
    print('Web平台: 设置CSRF Token和安全头');
    // 确保withCredentials标志已设置
    dio.options.extra['withCredentials'] = true;
  } else {
    print('非Web平台: 设置CSRF Token');
  }
  
  // 执行登录请求
  HttpUtil.getInstance().postForm(host + '/rest/login/', data, (responseData) {
    try {
      var parsedData = responseData is String ? jsonDecode(responseData) : responseData;
      if (cb != null) {
        cb(parsedData);
      }
    } catch (e) {
      print('解析登录响应失败: $e');
      if (errCallback != null) {
        errCallback(e);
      }
    }
  }, errCallback);
}

sql(cmd, callback) {
  get('/rest/sql/', {"cmd": cmd}, callback, () {});
}

void err_treat(e) {
  print(e);
}

void main() {
  login("马红权", "333333", (r) {
    print(r);
    contacts(null, (r) {
      print(r);
    }, err_treat);
  }, (e) {
    print(e);
  });
}
